console.log("content.js");

import { bitcoinmagazineArticle } from '@/content/components/bitcoinmagazine/index.js';
import { cryptoslateArticle } from '@/content/components/cryptoslate/index.js'
import { decryptArticle } from '@/content/components/decrypt/index.js'
import { cointelegraphArticle } from '@/content/components/cointelegraph/index.js'
// import axios from 'axios';

function initialize() {
    const currentUrl = window.location.href;
    console.log("当前页面的 URL:", currentUrl);
    if (currentUrl.includes('https://bitcoinmagazine.com/news') || currentUrl.includes('https://cryptoslate.com') || currentUrl.includes('https://decrypt.co') || currentUrl.includes('https://cointelegraph.com')) {
        // 检查是否有 token
        chrome.storage.local.get('token', (data) => {
            const token = data.token;
            console.log("当前页面是比特币杂志");
            console.log('登录接口');

            // 如果没有 token，则请求登录接口
            if (!token) {
                chrome.runtime.sendMessage({
                    type: "proxy",
                    method: "POST",
                    url: "/dex/auth/login",
                    body: { userName: "2HC5rCdVGiiEF7Wd", password: "securePassword123" }
                }, (response) => {
                    console.log(response);
                    let token = response.data.token;
                    chrome.storage.local.set({ token: token }, () => {
                        console.log("Token 已存储");
                    });
                    selectWebsite(currentUrl)
                    console.log(`[代理响应] 状态: ${response.code}, 数据: ${JSON.stringify(response.data)}`);
                });
            } else {
                console.log("已存在 token，直接进行后续操作");
                selectWebsite(currentUrl)
            }
        });
    }

}

function selectWebsite(currentUrl) {


    if (currentUrl.includes('https://bitcoinmagazine.com/news')) {
        bitcoinmagazineArticle()
    }
    // 处理其他网站的逻辑
    if (currentUrl.includes('https://cryptoslate.com')) {
        cryptoslateArticle();
    }
    if (currentUrl.includes('https://decrypt.co')) {
        decryptArticle();
    }
    if (currentUrl.includes('https://cointelegraph.com')) {
        cointelegraphArticle();
    }
}

// 监听 URL 变化
function monitorUrlChanges() {
    let lastUrl = window.location.href;

    // 监听 popstate 事件
    window.addEventListener('popstate', () => {
        if (window.location.href !== lastUrl) {
            lastUrl = window.location.href;
            console.log("popstate 事件触发");

            initialize();
        }
    });

    // 使用 MutationObserver 监听 DOM 变化
    const observer = new MutationObserver(() => {
        if (window.location.href !== lastUrl) {
            lastUrl = window.location.href;
            console.log("URL 变化了:", lastUrl);

            initialize();
        }
    });

    observer.observe(document, { childList: true, subtree: true });
}

// 初始化
window.onload = () => {
    initialize();
    monitorUrlChanges();
};

// window.addEventListener('message', (event) => {
//     if (event.data.type === 'crossOriginRequest') {
//         chrome.runtime.sendMessage({
//             type: 'proxy',
//             url: 'https://www.dextec.site' + event.data.path,
//             method: event.data.method
//         }, response => {
//             window.postMessage({
//                 type: 'crossOriginResponse',
//                 data: response
//             }, '*');
//         });
//     }
// });

// // 拦截 XMLHttpRequest
// (function () {
//     const originalXhrOpen = XMLHttpRequest.prototype.open;
//     XMLHttpRequest.prototype.open = function (method, url, ...args) {
//         console.log(`[XMLHttpRequest] 请求方法: ${method}, 请求地址: ${url}`);
//         // 判断是否需要走代理
//         if (url.startsWith("https://www.dextec.site")) {
//             console.log('shishishi');

//             chrome.runtime.sendMessage(
//                 {
//                     type: "proxy",
//                     method,
//                     url,
//                 },
//                 (response) => {
//                     console.log(`[代理响应] 状态: ${response.status}, 数据: ${response.data}`);
//                 }
//             );
//         }
//         this.addEventListener('load', function () {
//             console.log(`[XMLHttpRequest] 响应状态: ${this.status}, 响应数据: ${this.responseText}`);
//         });
//         return originalXhrOpen.call(this, method, url, ...args);
//     };
// })();

// // 拦截 fetch 请求
// (function () {
//     const originalFetch = window.fetch;
//     window.fetch = async function (input, init) {
//         const method = (init && init.method) || 'GET';
//         const url = typeof input === 'string' ? input : input.url;
//         console.log(`[Fetch] 请求方法: ${method}, 请求地址: ${url}`);
//         const response = await originalFetch(input, init);
//         const clonedResponse = response.clone();
//         clonedResponse.text().then((text) => {
//             console.log(`[Fetch] 响应状态: ${response.status}, 响应数据: ${text}`);
//         });
//         return response;
//     };
// })();
